package org.shalma.internal.reflection;

import java.lang.reflect.Field;

import org.shalma.internal.persistence.TranslatorManager;
import org.shalma.model.Entity;
import org.shalma.model.Entity.Key;
import org.shalma.model.Id;
import org.shalma.persistence.PersistenceException;
import org.shalma.persistence.Translator;

public class Property {

	private final byte[] id;

	private final Field field;

	private boolean indexed;

	@SuppressWarnings("rawtypes")
	private Translator translator;

	public Property(Field field) throws SecurityException,
			NoSuchMethodException {

		this.field = field;
		field.setAccessible(true);

		Id annotation = field.getAnnotation(Id.class);
		if (annotation == null)
			throw new PersistenceException(field.getDeclaringClass(),
					"@Id not found for field " + field);

		id = IdGenerator.decodeURL(annotation.value());

		final Class<?> clazz = field.getType();

		translator = getMapper().getTranslator(clazz);
		if (translator == null)
			throw new PersistenceException(clazz, "Translator not found.");

		if (Key.class.isAssignableFrom(clazz))
			indexed = true;
	}

	// @SuppressWarnings("unchecked")
	// public void setProperty(Entity entity,
	// com.google.appengine.api.datastore.Entity apiEntity)
	// throws IllegalArgumentException, IllegalAccessException,
	// InstantiationException, InvocationTargetException {
	//
	// Object data = apiEntity.getProperty(id);
	// if (data == null)
	// return;
	//
	// data = translator.toType(data);
	//
	// field.set(entity, data);
	// }

	public byte[] getId() {
		return id;
	}

	@SuppressWarnings("unchecked")
	public Object read(Entity entity) throws IllegalArgumentException,
			IllegalAccessException {

		Object data = field.get(entity);

		if (data != null)
			data = translator.toProperty(data);

		return data;
	}

	public String toString() {
		return id + "[" + field.getType().getName() + "]";
	}

	private TranslatorManager getMapper() {
		return null;
	}
}